package com.zros.modules.business.controller;


import io.swagger.annotations.ApiOperation;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zros.common.api.vo.PageResult;
import com.zros.common.api.vo.Result;
import com.zros.common.exception.JeecgBootException;
import com.zros.modules.business.entity.Channel;
import com.zros.modules.business.entity.Clue;
import com.zros.modules.business.service.IChannelService;
import com.zros.modules.business.service.IClueService;
import com.zros.modules.business.vo.ChannelVo;
import com.zros.modules.shiro.authc.util.JwtUtil;
import com.zros.modules.system.dto.UserInfo;
import com.zros.modules.system.service.IUserService;

/**
 * <p>o
 * 渠道表 前端控制器
 * </p>
 *
 * @author pangyinqiang
 * @since 2019-04-20
 */
@RestController
@RequestMapping("/business/channel")
@PropertySource("classpath:config.properties")
public class ChannelController 
{
	@Value("${authority.campusKey}")
	private String authorityCampusKey;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IChannelService channelService;
	
	@Autowired
	private IClueService clueService;
	
	/**
	 * 分页查询渠道
	 */
	@ApiOperation(value = "分页查询渠道")
	@RequiresPermissions("business:channel:list")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public PageResult<ChannelVo> queryPageList(HttpServletRequest request, Page<ChannelVo> page, Channel channel)
	{
		//获取当前用户
		UserInfo currentUser = queryCurrentUser(request,"queryChannelType");
		//获取数据权限key
		String dataResourceKey = currentUser.getDataResourceKey();
		if(StringUtils.isEmpty(dataResourceKey))
		{
			throw new JeecgBootException("数据权限查询不到！请联系管理员！");
		}
		
		//校区权限，查询自己所属校区渠道类型
		if(authorityCampusKey.equals(dataResourceKey))
		{
			channel.setUserId(currentUser.getId());
		}
		
		Page<ChannelVo> pageChannel = channelService.queryList(page,channel);
        PageResult<ChannelVo> pageResult = new PageResult<ChannelVo>(pageChannel.getTotal(), pageChannel.getRecords());
		return pageResult;
		
	}
	
	/**
	 * 添加渠道
	 */
	@ApiOperation(value = "添加渠道")
	@RequiresPermissions("business:channel:list")
	@PostMapping("/create")
	public Result<?> create(@RequestBody Channel channel) 
	{
		QueryWrapper<Channel> ew = new QueryWrapper<>();
        ew.eq("channel_name", channel.getChannelName()).
        	eq("channel_type_id", channel.getChannelTypeId());
        List<Channel> roleList = channelService.list(ew);
        if (!CollectionUtils.isEmpty(roleList)) {
            throw new JeecgBootException("渠道名称在该渠道类型中已经存在！");
        }
		
		return new Result<>().success(channelService.save(channel) ? "添加成功" : "添加失败，请重试");
	}

	/**
	 * 修改渠道
	 */
	@ApiOperation(value = "修改渠道")
	@RequiresPermissions("business:channel:list")
	@PostMapping("/update")
	public Result<?> update(@RequestBody Channel channel)
	{
		QueryWrapper<Channel> ew = new QueryWrapper<>();
        ew.ne("channel_id", channel.getChannelId()).
        	eq("channel_name", channel.getChannelName()).
        	eq("channel_type_id", channel.getChannelTypeId());
        List<Channel> roleList = channelService.list(ew);
        if (!CollectionUtils.isEmpty(roleList)) {
            throw new JeecgBootException("渠道名称在该渠道类型中已经存在！");
        }
		
		return new Result<>().success(channelService.updateById(channel) ? "修改成功" : "修改失败，请重试");
	}

	/**
	 * 删除渠道
	 */
	@ApiOperation(value = "删除渠道")
	@RequiresPermissions("business:channel:list")
	@PostMapping("/delete/{id}")
	public Result<?> delete(@PathVariable("id") Long id) {
		if (null == id) {
			return new Result<>().error("ID不能为空");
		}
		
		QueryWrapper<Clue> ew = new QueryWrapper<>();
        ew.eq("channel_id", id);
        List<Clue> roleList = clueService.list(ew);
        if (!CollectionUtils.isEmpty(roleList)) {
            throw new JeecgBootException("该渠道已被线索使用，不可删除！");
        }
		
		return new Result<>().success(channelService.removeById(id) ? "删除成功" : "删除失败，请重试");
	}
	
	/**
	 *  获取当前用户
	 */
	UserInfo queryCurrentUser(HttpServletRequest request,String queryMethod)
	{
		UserInfo currentUser = new UserInfo();
		String userAccount = JwtUtil.getUserAccountByToken(request);
		currentUser = userService.queryUserInfoByAccount(userAccount,queryMethod);
		
		return currentUser;
	}
}
